package edu.xidian.forum.jwt;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final PathMatcher pathMatcher = new AntPathMatcher();

    private static final List<String> protectList = new ArrayList<>();

    // TODO 收集受保护的URL
    static {
        protectList.add("/user/info");
        protectList.add("/user/update");
        protectList.add("/user/upload_avatar");
        protectList.add("/post/create");
        protectList.add("/post/update");
        protectList.add("/post/like");
        protectList.add("/post/unlike");
        protectList.add("/post/hasliked");
        protectList.add("/post/delete");
        protectList.add("/comment/add_comment");
        protectList.add("/user/updatePassword");
        protectList.add("/user/checkUserPassword");
        protectList.add("/user/updateEmail");
        protectList.add("/relationship/subscribe/*");
        protectList.add("/relationship/unsubscribe/*");
        protectList.add("/relationship/validate/*");
        protectList.add("/billboard/add");
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            if (isProtectedUrl(request)) {
                if (!request.getMethod().equals("OPTIONS")) {
                    request = JwtUtil.validTokenAndAddIdToHeader(request);
                }
            }
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
            return;
        }
        filterChain.doFilter(request, response);
    }

    private boolean isProtectedUrl(HttpServletRequest httpServletRequest) {
        boolean bFind = false;
        for (String passedPath : protectList) {
            bFind = pathMatcher.match(passedPath, httpServletRequest.getServletPath());
            if (bFind) {
                break;
            }
        }
        return bFind;
    }
}
